//将卡迪尔坐标转换为经纬度

function Cartesian3_to_WGS84(point)
{
    var c3 = new Cesium.Cartesian3(point.x,point.y,point.z);
    var cartofraphic = Cesium.Cartographic.fromCartesian(c3);
    var lon = Cesium.Math.toDegrees(cartofraphic.longtitude).toFixed(1);
    var lat = Cesium.Math.toDegrees(cartofraphic.latitude).toFixed(1);
    var alt= cartofraphic.height.toFixed(4);
    return {lon:lon , lat:lat, alt:alt};
}

//返回位置属性 
function computeFlight(source){
    var property = new Cesium.SampledPositionProperty();
    let stime = Cesium.JulianDate.addSeconds(viewer.clock.startTime,source[0].time,new Cesium.JulianDate());
    property.addSample(Cesium.JulianDate.addSeconds(stime,0,new Cesium.JulianDate()),
        Cesium.Cartesian3.fromDegrees(source[0].lon,source[0].lat,source[0].alt));
    for(var i=0;i<source.length;i++){
        let time = Cesium.JulianDate.addSeconds(stime,source[i].time-source[0].time+3.5,new Cesium.JulianDate());
        let position = Cesium.Cartesian3.fromDegrees(source[i].lon,source[i].lat,source[i].alt);
        property.addSample(time,position);
    }
    return property;
}

var timeLen;//定义演示总时长
let timecount = 0; //控制只在接收第一条数据使,初始化时间轴
let hasCreateEntitiesArr=[];//存放场景中已经加载的实体id

function resoloveData(data){
    //传入的蚕食data为当前时间点的所有数据，为数组
    for(var i=0;i<data.length;i++){
        var object = JSON.parse(data[i]);//转为json对象
        var type = object.msgType;
        var content = object.content;

        /*
            实体已经存在的前提下，处理改组接收数据中已经加载但没有位置数据的实体，
            如果不做处理，实体会在场景中消失，对每天接收到的数据分为以下情况：
            1.该数据的msgType扔为nodeInfo
        */
       if(type == 'nodeInfo'){
           //倍速后改变timetag为实际接收到数据的时刻
           if(timecount==0){
               for(var j=0;j<content.length;j++){
                   content[j].timetag=0;
               }
           }else{
               //判断接收数据时刻，作为新属性timetag插入原有json串，改变实体位置时需要改属性
               let start_time = Cesium.JulianDate.toDate(viewer.clock.startTime).valueOf();
               let current_time = Cesium.JulianDate.toDate(viewer.clock.currentTime).valueOf();
               let timetag = ((current_time - start_time)/1000).toFixed(4);
               for(var j=0;j<content.length;j++){
                   content.timetag =timetag;
               }
           }

           for(var newIndex = 0;newIndex<hasCreateEntitiesArr.length;newIndex++){
               let count = 0;
               let starticEntity = viewer.entities.getById(hasCreateEntitiesArr[newIndex]);
               if(timecount!=0){
                   for(var j = 0;j<content.length;j++){
                       if(hasCreateEntitiesArr[newIndex] != content[j].id){
                           count++;
                       }
                   }
               }
               //给改组数据中未出现位置的数据但已经在场景中加载的实体静止位置信息，保证不会消失在场景中
               if(count == content.length){
                   if(!starticEntity.is_static&&starticEntity.data.length>1){
                       let len = starticEntity.data.length;
                       let longtitude1 = starticEntity.data[len-2].lon;
                       let latitude1 =  starticEntity.data[len-2].lat;
                       let longtitude2 = starticEntity.data[len-1].lon;
                       let latitude2 =  starticEntity.data[len-1].lat; 
                       let height = starticEntity.data[len-1].alt;
                       let longitude  = starticEntity.side ==='blue'?longtitude2-0.0001:longtitude2+0.0001;

                       /*
                            在该实体最终位置上增加新的位置样本，时间点定位到态势方案结束时间之后，
                            位置定位到和最后给出的位置不限接近，制造视觉上的静止状态，但是要保证和原来的朝向相同
                       */

                       if(longtitude1 !=longtitude2){
                           var latitude = latitude2 -(latitude1-latitude2)*(longtitude2-longitude)/(longtitude1-longtitude2);
                       }else{
                           var latitude = latitude2 - (latitude1-latitude2)*(longtitude2-longitude);
                       }
                       starticEntity.data.push({lon:longitude,lat:latitude,alt:height,time:timeLen});
                       let property = computeFlight(starticEntity.data);
                       starticEntity.position = property;
                       starticEntity.orientation = new Cesium.VelocityOrientationProperty(starticEntity.position);

                       //将该项设置为true是保证不会重复为这种条件下实体复制“静止”位置
                       starticEntity.is_static=true;
                   }
               }
           }
       }

       //另外一种不需要改变时间的方法，
       //接收倍速消息，解析消息，拨快时间轴的播放速度
       switch(type){
           case 'nodeInfo':
               //初始化开始传输数据的时间
               if(timecount=0){
                   //获取系统当前时间
                   let time = new Date();
                   let year = time.getFullYear();
                   let month = time.getMonth()+1;
                   let date = time.getDate();
                   let hour = time.getHours();
                   let minutes = time.getMinutes();
                   let second = time.getSeconds();
                   let start = Cesium.JulianDate.fromDate(new Date(year,month,date,hour,minutes,second));
                   let stop = Cesium.JulianDate.addSeconds(start,timeLen,new Cesium.JulianDate());
                   viewer.clock.startTime = start.clone();
                   viewer.clock.currentTime = start.clone();
                   viewer.clone.stopTime = stop.clone();
                   viewer.clock.clockRange  = Cesium.ClockRange.CLAMPED;
                   viewer.clock.multiplier = 1;
               }
               timecount++;
               createNode(object); break;
               case 'linkInfo':
               createLink(content); break;
               case 'eventInfo':
                   createEvent(conteng);break;
       }
    }
}

//初始化，移除新场景中所有实体
function init(){
    viewer.entities.removeAll();
    hasCreateEntitiesArr=[];
    location.reload();
}

//计算两点间的距离

function computeDistance(lon1,lat1,lon2,lat2){
    let R = 6371;
    let dLat = (lat2 - lat1)* Math.PI/180;
    let dLon = (lon2 - lon1)* Math.PI/180;
    let a = Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(lat*Math.PI/180)*
            Math.cos(lat2*Math.PI/180)*Math.sin(dLon/2)*Math.sin(dLon/2);
    let c = 2*Math.asin(Math.sqrt(a));
    return R*C*1000;
}

/*
    根据两点计算两点间的航向角，俯仰角
    由于场景中未涉及俯仰角，俯仰角始终为默认值，故只需要计算航向角
*/
function headingPitch(lon1,lat1,lon2,lat1){
    let btmX = computeDistance(lon1,lat1,lon2,lat1);//计算两个飞机球面距离，假设位于同一水平面
    let jdC1 = computeDistance(lon1,lat1,lon2,lat1);//源纬度经度差
    let jdC0 = computeDistance(lon1,lat2,lon2,lat2);//目标经纬度差
    let lonCha = lon1-lon2,latCha = lat1-lat2;
    /*
        判断偏航角、俯仰角计算方式
        位于第一象限，经度差<0，纬度差<0，-acos(纬度差/球面距离)，
        位于第二象限，经度差>0，纬度差<0，-{asin(经度差/球c面距离)+Cesium.Math.toRadians(90)},
        位于第三象限，经度差>0，纬度差>0,asin(经度差/球面距离)+Cesium.Math.toRadians(90),
        位于第四象限，经度差>0,acos(经度差/球面距离)
    */
   let heading = 0.0;
   let trigValue = (jdC0-(jdC1-jdC0)/2)/btmX;
   if(lonCha<0&&latCha<0)
   {
       trigValue>1?heading= -Math.acos(1):heading = -Math.acos(trigValue);
   }
   if(lonCha>0&&latCha<0)
   {
        trigValue>1?heading = -(Math.asin(1)+Cesium.Math.toRadians(90)):heading = -(Math.asin(trigValue)+Cesium.Math.toRadians(90));
   }
   if(lonCha>0&&latCha>0)
   {
    trigValue>1?heading = Math.asin(1)+Cesium.Math.toRadians(90):heading = Math.asin(trigValue)+Cesium.Math.toRadians(90);
   }
   if(lonCha<0&&latCha>0)
   {
    trigValue>1?heading = Math.acos(1):heading = Math.acos(trigValue);
   }
   return heading;
}